var express = require('express');
var router = express.Router();

const db = require("../utils/dbconfig");
const { json } = require('body-parser');

// 判定登陆账号是否存在
router.get('/login', function (req, response, next) {
  let sql = 'select * from user where  account=? and password=?'
  console.log(req.query)
  let params = Object.values(req.query)
  console.log(params)

  db.sqlConnection(sql, params).then((res) => {
    console.log("res:", res[0])
    if (res[0]) {

      console.log("登陆成功了", res)
      response.header("Access-Control-Allow-Origin", "*");
      response.send(res);

    } else {
      response.header("Access-Control-Allow-Origin", "*");
      console.log("账号或者密码输入错误", res)
      response.send(res)
    }
  })
});

// 提交注册账号
router.post('/', function (req, res, next) {
  let sql = 'insert into user(account,password,nickname,type) value(?,?,?,?)';
  let params = [req.body.account, req.body.password, req.body.nickname, req.body.type];
  res.header("Access-Control-Allow-Origin", "*");

  db.sqlConnection(sql, params)
    .then((result) => {
      console.log('res:', result);

      res.send('注册成功');
    })
    .catch((err) => {
      console.error('Error:', err);
      res.status(500).send('注册失败');
    });
});

//获取用户报名活动列表
router.get('/activity_attend', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log(" req.query:", req.query)
  let data = req.query
  let params = []
  let sql = `SELECT * FROM activity WHERE activityId IN (SELECT activityId FROM activity_attend WHERE userId = '${data.id}');`
  // 'INSERT INTO users SET ?
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("获取失败")
  })
});

//参与此项活动的人员
router.get('/activity_attend_users', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log(" req.query:", req.query)
  let data = req.query
  let params = []
  let sql = `SELECT * FROM user WHERE userId IN (SELECT userId FROM activity_attend WHERE activityId = '${data.id}');`
  // 'INSERT INTO users SET ?
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("获取失败")
  })
});

// 通过用户id获取用户的购物车数据
router.get('/shopping_cart', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log(" req.query:", req.query)
  let params = []
  let sql = `SELECT shopping_cart_id, s.userId, s.goodsId, goodsName, goodsImage, goodsArticle, goodsIntroduce, goodsPrice, goodsType,goodsCount
FROM shopping_cart s 
INNER JOIN goods g
ON s.goodsId = g.goodsId
WHERE s.userId='${req.query.id}' `;
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("未搜索到")
  })
});
//插入购物车活动信息
router.post('/shopping_cart', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log("req.body:", req.body)
  let params = {
    goodsId: req.body[0],
    userId: req.body[1]
  }
  let sql = `insert into shopping_cart set ?`;
  // 'INSERT INTO users SET ?
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("插入失败")
  })
});
//修改购物车内单品的数量信息
router.post('/shopping_cart/addCount', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log("req.body:", req.body)
  let params = []
  let sql = `update shopping_cart set goodsCount='${req.body[1]}' where shopping_cart_id ='${req.body[0]}' `;
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("插入失败")
  })
});
//删除购物车内单品
router.post('/shopping_cart/delete', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log("req.body:", req.body)
  let params = []
  let sql = `DELETE FROM shopping_cart WHERE shopping_cart_id ='${req.body.id}' `;
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send("删除成功")
  }).catch((err) => {
    console.log(err)
    res.send("删除失败")
  })
});

// 通过用户id获取用户的购物地址信息
router.get('/address', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log(" req.query:", req.query)
  let params = []
  let sql = `SELECT * FROM address WHERE userId='${req.query.id}' `;
  // 'INSERT INTO users SET ?
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("未搜索到")
  })
});
//插入购物地址信息
router.post('/address', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log("req.body:", req.body)
  let params = req.body
  let sql = `insert into address set ?`;
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("插入失败")
  })
});
//更新购物地址信息
router.post('/address/updata', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log("req.body:", req.body)
  let params = req.body
  let sql = `update address set ? where address_id =${req.body.address_id} `;
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("插入失败")
  })
});
//删除购物地址信息
router.post('/address/delete', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log("req.body:", req.body)
  let params = req.body
  let sql = `DELETE FROM address WHERE address_id ='${req.body[0]}' `;
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send("删除成功")
  }).catch((err) => {
    console.log(err)
    res.send("删除失败")
  })
});

//插入订单信息
router.post('/order_pay', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log("req.body:", req.body);
  let { address, goods, userId, order_number, order_data } = req.body;
  // 数据验证
  if (!address || !goods || !userId || !order_number || !order_data) {
    return res.status(400).send({ error: "缺少必要的字段" });
  }
  let data = {
    address: typeof address === 'string' ? address : JSON.stringify(address),
    goods: typeof goods === 'string' ? goods : JSON.stringify(goods),
    order_data,
    order_number,
    userId,
  };
  let sql = `insert into orders (address, goods, order_data, order_number, userId) values (?, ?, ?, ?, ?)`;
  let params = [data.address, data.goods, data.order_data, data.order_number, data.userId];
  console.log("params:", params);

  db.sqlConnection(sql, params)
    .then((result) => {
      res.send(result);
    })
    .catch((err) => {
      console.error(err);
      res.status(500).send({ error: "插入失败", details: err.message });
    });
});
// 通过 userId 获取订单信息
router.get('/order', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  let { userId } = req.query;

  // 数据验证
  if (!userId) {
    return res.status(400).send({ error: "缺少必要的字段: userId" });
  }

  let sql = `SELECT * FROM orders WHERE userId = ?`;
  let params = [userId];

  db.sqlConnection(sql, params)
    .then((result) => {
      if (result.length === 0) {
        return res.status(404).send({ error: "未找到相关订单信息" });
      }
      result = result.map(order => {
        return {
          ...order, // 保留其他字段
          address: JSON.parse(order.address), // 解析 address 字段
          goods: JSON.parse(order.goods) // 解析 goods 字段
        };
      });
      console.log(result)
      res.send(result);
    })
    .catch((err) => {
      console.error(err);
      res.status(500).send({ error: "查询失败", details: err.message });
    });
});

router.get('/forumData', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log(" req.query:", req.query)
  let params = []
  let sql = `SELECT forumId, f.userId, forumTitle, forumMessage, forumCreatTime,account,nickname,image
FROM forum f
INNER JOIN user u
ON f.userId = u.userId`;
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("未搜索到")
  })
});

// 插入论坛帖子回复信息
router.post('/forum/post', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log("req.body:", req.body);

  let sql = `insert into forum_post ( forumId, userId, postMessage) values (?, ?, ?)`;
  let params = [req.body.forumId, req.body.userId, req.body.postMessage];
  console.log("params:", params);

  db.sqlConnection(sql, params)
    .then((result) => {
      res.send(result);
    })
    .catch((err) => {
      console.error(err);
      res.status(500).send({ error: "插入失败", details: err.message });
    });
});
// 通过 forumId 获取帖子回复数据，并关联 user 表
router.get('/forum/post', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  let forumId = req.query.forumId; // 从查询参数中获取 forumId
  console.log("拉屎都放假欧文哦io放假了", req.query)
  let sql = `
    SELECT 
      fp.postId, fp.postMessage, 
      fp.userId, u.nickname, u.account
    FROM 
      forum_post fp
    JOIN 
      user u ON fp.userId = u.userId
    WHERE 
      fp.forumId = ?
  `;

  let params = [forumId];

  db.sqlConnection(sql, params)
    .then((result) => {
      res.send(result);
    })
    .catch((err) => {
      console.error(err);
      res.status(500).send({ error: "查询失败", details: err.message });
    });
});
// 通过获取用户发布过的帖子
router.get('/forum/id', function (req, response, next) {
  response.header("Access-Control-Allow-Origin", "*");

  let sql = 'select * from forum where userId=?'
  console.log(req.query)
  let params = Object.values(req.query)
  console.log(params)

  db.sqlConnection(sql, params).then((res) => {
    console.log("res:", res[0])
    if (res[0]) {

      console.log("登陆成功了", res)
      response.send(res);
    } else {
      console.log("账号或者密码输入错误", res)
      response.send(res)
    }
  })
});

// 通过获取商家发布的商品
router.get('/merchant/goods', function (req, response, next) {
  response.header("Access-Control-Allow-Origin", "*");

  let sql = 'select * from goods where userId=?'
  // console.log(req.query)
  let params = Object.values(req.query)
  // console.log(params)

  db.sqlConnection(sql, params).then((res) => {
    if (res[0]) {
      // console.log("成功了", res)
      response.send(res);
    } else {
      // console.log(res)
      response.send(res)
    }
  })
});
// 通过id删除商家发布的商品
router.post('/merchant/goods/delete', function (req, response, next) {
  response.header("Access-Control-Allow-Origin", "*");

  let sql = `DELETE FROM goods where goodsId='${req.body.goodsId}'`
  // console.log(req.query)
  let params = Object.values(req.body)
  console.log(params)
  db.sqlConnection(sql, params).then((res) => {
    response.send(res);
  }).catch((err) => {
    // console.log(err)
    response.send("删除失败")
  })
});

module.exports = router;